<?php
namespace app\kucun\controller;

use app\exception\ApiException;
use app\kucun\model\WxWorkUserModel;
use think\admin\Controller;

/**
 * Class Index
 * @package app\index\controller
 */
class Base extends Controller
{
    public $token = '';
    public $user = null;
    public $token_login_info = null;

    public function __construct(\think\App $app)
    {
        parent::__construct($app);
        $token = request()->header('token');
        $this->token = $token;
        $login_info = null;
        if($token){
            $login_info = cache($token);
        }else{
            if(env('env.local_uid')){
                $this->user = WxWorkUserModel::where('id', env('env.local_uid'))->find();
            }
        }


        // 这里再兼容一下cookie的写法
        if(!$login_info){
            $login_info = cookie("login_info");
        }
        if($login_info){

            if(is_string($login_info)){
                $login_info = json_decode($login_info, true);
            }

            $this->token_login_info = $login_info;
            $this->user = $login_info;
        }
    }

    /**
     * 检测当前用户是否已登录
     * @return mixed
     */
    public function checkUserLogin(){
        if($this->user == null){
            throw new ApiException('用户登录失效，请登录后重试', 401);
        }
    }

    /**
     * 通用返回成功方法
     * @return mixed
     */
    public function returnSuccess($data, $message = 'success', $code = 200){
        return json(['code' => $code, 'msg' => $message, 'data' => $data]);
    }

    public function returnError($data, $message = 'success', $code = 500){
        return json(['code' => $code, 'msg' => $message, 'data' => $data]);
    }

}